/**
 * @discription 极光推送实现工具类
 * @author chenling   
 * @created 2017-5-6 上午8:52:15
 */  
package com.solution.common.utils.jpush;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

  
 /**
 * Title: JpushUtil.java 
 * Description: 极光推送工具类
 * @author chenling    
 * @created 2017-5-6 上午8:53:15
 */
public class JpushUtil {
	
	private static Logger logger=Logger.getLogger(JpushUtil.class);
	
	//极光推送授权AppKey 测试
	public static final String appKeyTest="68641329c8f1e752fc07054c";
	//极光推送授权masterSecret 测试
	public static final String masterSecretTest="4dac566420d63046d2c88f86";
	
	//极光推送授权AppKey 正式
	public static final String appKey="91e5f8155af2424d6176734e";
	//极光推送授权masterSecret 正式
	public static final String masterSecret="7956b26d8cdf1826aaad3e90";
	
	
	//极光推送自定义推送声音
	public static final String sound="happy.caf";
	/**
     * @discription 构建推送对象：所有ios平台(通知消息)
     * @author chenling  
     * @param registrationId 推送目标是别名为 "registrationId"
     * @param alert 通知内容为 alert
     * @param msgContent 推送信息为msgContent
     * @created 2017-5-6 上午9:01:32
     * @return
	 */
	public static PushPayload sendNoticeToIos(String registrationId,String alert,String msgContent) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(registrationId))
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .setNotification(Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
						                .setAlert(alert)
						                .setSound(sound)
						                .addExtra("message", msgContent)
						                .build())
						         .build())
                //.setMessage(Message.newBuilder().setMsgContent(msgContent).addExtra("from", "JPush").build())
                .build();
    }
	/**
     * @discription 构建推送对象：所有ios平台(自定义消息)
     * @author chenling  
     * @param registrationId 推送目标是别名为 "registrationId"
     * @param 通知内容为 alert
     * @param 推送信息为msgContent
     * @created 2017-5-6 上午9:01:32
     * @return PushPayload
	 */
	public static PushPayload sendMsgToIos(String registrationId,String alert,String msgContent) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .build())
                .build();
    }
	
	/**
	 * 
     * @discription 构建推送对象：android平台(通知消息)
     * @author chenling  
     * @param aliasId 推送目标是别名为 "alias1"
     * @param alert 通知内容为 alert
     * @param msgContent 推送信息为msgContent
     * @created 2017-5-6 上午9:21:32
     * @return
	 */
	public static PushPayload sendNoticeToAndroid(String aliasId,String alert,String msgContent,String title,String contentType,Map<String, Object> JsonStr) {
        String extraValue=JSON.toJSONString(JsonStr);
		return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(aliasId))
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .setNotification(Notification.newBuilder()
                				.addPlatformNotification(AndroidNotification.newBuilder()
								.setAlert(alert)
								.setTitle(title)
								.build())
                				.build())
                .setMessage(Message.newBuilder()
                		    .setMsgContent(msgContent)
                		    .setContentType(contentType)
                			.addExtra("extraValue", extraValue)
                			.build())
                .build();
    }
	/**
     * @discription 构建推送对象：所有ios平台(自定义消息)
     * @author chenling  
     * @param registrationId 推送目标是别名为 "registrationId"
     * @param 通知内容为 alert
     * @param 推送信息为msgContent
     * @created 2017-5-6 上午9:01:32
     * @return PushPayload
	 */
	public static PushPayload sendMsgToAndroid(String alias,String alert,String msgContent) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "infomation")
                                .setAlert(alert)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .build())
                .build();
    }
	/**
     * @discription 构建推送对象：所有平台
     * @author dujiewei
     * @param aliasId 推送目标是别名为 "alias1"
     * @param alert 通知内容为 alert
     * @param msgContent 推送信息为msgContent
     * @created 2015-11-24 下午4:22:32
     * @return
	 */
	public static PushPayload buildPushObjectAllAliasAlert(String aliasId,String alert,String msgContent) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(aliasId))
                .setNotification(Notification.alert(alert))
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .setMessage(Message.newBuilder().
                			setMsgContent(msgContent)
                			.addExtra("from", "JPush")
                			.build())
                .build();
    }
	/**
     * @discription 构建推送对象：平台是 iOS，推送目标是 "tag1", "tag_all" 的交集，
     * 推送内容同时包括通知与消息 - 通知信息是 ALERT，角标数字为 5，通知声音为 "happy"，
     * 并且附加字段 from = "JPush"；消息内容是 MSG_CONTENT。通知是 APNs 推送通道的，
     * 消息是 JPush 应用内消息通道的。APNs 的推送环境是“生产”（如果不显式设置的话，Library 会默认指定为开发）
     * @author dujiewei  
     * @param alter 通知内容为 alert
     * @param msgContent 推送信息为msgContent
     * @created 2015-11-24 下午4:26:31
     * @return
	 */
	public static PushPayload buildPushObjectIosTagAndAlertWithExtrasAndMessage(String alter,String msgContent) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(alter)
                                .setBadge(5)
                                .setSound("happy.caf")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                 .setMessage(Message.content(msgContent))
                 .setOptions(Options.newBuilder()
                         .setApnsProduction(true)
                         .build())
                 .build();
    }
	/**
     * @discription 构建推送对象：平台是 Andorid 与 iOS，
     * 推送目标是 （"tag1" 与 "tag2" 的并集）且（"alias1" 与 "alias2" 的并集），
     * 推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush。
     * @author dujiewei  
     * @param alter 通知内容为 alert
     * @param msgContent 推送信息为msgContent
     * @created 2015-11-24 下午5:22:16
     * @return
	 */
	public static PushPayload buildPushObjectIosAudienceMoreMessageWithExtras(String alter,String msgContent) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(msgContent)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }
	/**
     * @discription 极光推送到用户通知
     * @author chenling  
     * @created 2017-5-6 上午10:07:47
     * @param  aliasId 推送别名
     * @param  alterContent 提示信息
     * @param  msgContent 推送信息内容
     * @param  terminalType 推送手机型号(ios,android)
	 */
	public static void sendNotice(String aliasId,String alterContent,String msgContent,String terminalType,String title,String contentType,Map<String, Object> jsonStr){
		JPushClient jpushClient = new JPushClient(masterSecretTest, appKeyTest,3);
        // For push, all you need do is to build PushPayload object.
		//发送极光封装参数对象
        PushPayload payload =null;
          //别名推送（暂时只用到别名推送）  通知发送
    	  if("ios".equals(terminalType)){
    		payload=sendNoticeToIos(aliasId,alterContent,msgContent);
  	      }
  	      if("android".equals(terminalType)){
  	    		payload=sendNoticeToAndroid(aliasId,alterContent,msgContent,title,contentType,jsonStr);
  	      }
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println("ssss:"+payload);
            logger.info("Got result - " + result);

        } catch (APIConnectionException e) {
        	logger.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
        	logger.error("Should review the error, and fix the request", e);
        	logger.info("HTTP Status: " + e.getStatus());
        	logger.info("Error Code: " + e.getErrorCode());
        	logger.info("Error Message: " + e.getErrorMessage());
        }	
	}
	/**
     * @discription 极光推送到用户自定义消息
     * @author chenling  
     * @created 2017-5-6 上午10:17:47
     * @param  aliasId 推送别名
     * @param  alterContent 提示信息
     * @param  msgContent 推送信息内容
     * @param  terminalType 推送手机型号(ios,android)
	 */
   public static void sendCustomMsg(String registrationId,String alterContent,String msgContent,String terminalType){
	   ClientConfig config = ClientConfig.getInstance();
       config.setMaxRetryTimes(5);
       config.setConnectionTimeout(10 * 1000); // 10 seconds
       config.setSSLVersion("TLSv1.1");        // JPush server supports SSLv3, TLSv1, TLSv1.1, TLSv1.2
       JPushClient jPushClient = new JPushClient(masterSecretTest, appKeyTest, null, config);
        // For push, all you need do is to build PushPayload object.
		//发送极光封装参数对象
        PushPayload payload =null;
        //别名推送(android 使用别名推送,ios 使用登记id) 
        if("ios".equals(terminalType)){
    		 payload=sendMsgToIos(registrationId,alterContent,msgContent);
         }
        if("android".equals(terminalType)){
        	 payload=sendMsgToAndroid(registrationId,alterContent,msgContent);
        }
        try {
            PushResult result = jPushClient.sendPush(payload);
            System.out.println("ssss:"+payload);
            logger.info("Got result - " + result);
        } catch (APIConnectionException e) {
        	logger.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
        	logger.error("Should review the error, and fix the request", e);
        	logger.info("HTTP Status: " + e.getStatus());
        	logger.info("Error Code: " + e.getErrorCode());
        	logger.info("Error Message: " + e.getErrorMessage());
        }	
	}
	
	public static void main(String[] args){

		String alterContent="您的账号已在另一处登录，如果不是您本人操作，请尽快修改密码！";
		String msgContent="测试通知";
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		jsonStr.put("from", "Jpush");
		jsonStr.put("messageId", "8");
		//通知部分
		/**
		 * 翟二远：bd8d9dd77c6156bfca528fdc69ee2ee0
		 * 周少寒：bad585320c0faff60b0cc47ea97f5c1c
		 * 陈    凌：
		 */
		JpushUtil.sendNotice("bd8d9dd77c6156bfca528fdc69ee2ee0", alterContent, msgContent,"android","消息推送","stationMsg",jsonStr);
		//JpushUtil.sendNotice("1114a89792991840986", alterContent, msgContent,"ios");
        //自定义消息部分
		//JpushUtil.sendCustomMsg("1114a89792991840986", alterContent, msgContent,"ios");
		//JpushUtil.sendCustomMsg("406ba0d99c293d2abeb3c7911d482a13", alterContent, msgContent,"android");  
		
	}
}
